import { ISA } from '@/atmosphere'
import { kt2Mps, m2ft, mps2Kt } from '@/widgets'
import { getBADAModel } from './core'
import type { OperationPerformance } from './types'
import { calcMaxClimbThrust } from './thrust-alt'
import { calcNormalDrag } from './drag-tas'

interface Options {
  ESF: number
  PWC: number
  alt: number
}

export interface ROCSpdItem {
  drag: number
  ROC: number
  TAS: number
  CAS: number
  mach: number
}

export interface ROCSpdProfile {
  thrust: number
  ESF: number
  PWC: number
  alt: number
  mass: number
  line: ROCSpdItem[]
}

export function calcRocSpdProfileById(code: string, opts: Options): ROCSpdProfile {
  const model = getBADAModel(code)!
  return calcRocSpdProfile(model.performance, opts)
}

function calcRocSpdProfile(op: OperationPerformance, opts: Options): ROCSpdProfile {
  const { alt, ESF, PWC } = opts
  const ad = ISA.getAirData(opts.alt)
  const minKCAS = op.vStallIC * 1.3
  const maxKCAS = Math.min(op.vMO, mps2Kt(ad.mach2CAS(op.machMO)))
  // console.log('minKCAS', minKCAS, maxKCAS, op.vMO, op.machMO, ad, ad.mach2CAS(op.machMO))
  let kCAS = Math.ceil(minKCAS / 10.0) * 10.0
  const altFt = m2ft(opts.alt)
  const thrust = calcMaxClimbThrust(kCAS, altFt, op)
  const mass = op.massRef * 1000.0

  const G0 = 9.80665
  const line: ROCSpdItem[] = []
  while (kCAS < maxKCAS) {
    const CAS = kt2Mps(kCAS)
    const TAS = ad.CAS2TAS(CAS)
    const mach = ad.TAS2Mach(TAS)
    const drag = calcNormalDrag(op, ad, TAS)
    const ROC = (((thrust - drag) * TAS) / mass / G0) * ESF * PWC
    line.push({ drag, ROC, TAS, CAS, mach })
    kCAS += 10.0
  }
  return { line, thrust, ESF, mass: mass / 1000.0, PWC, alt }
}
